package com.company.common.server.aes;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class AESUtils {

    private static final Logger logger = LoggerFactory.getLogger(AESUtils.class);

    /**
     * 加密返回,Base64编码字符串
     *
     * @param input 待加密内容
     * @param key   加密密钥
     * @return
     */
    public static String encrypt(String input, String key) {
        byte[] crypted = null;
        try {
            SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, skey);
            crypted = cipher.doFinal(input.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (crypted == null) {
            logger.warn("加密结果为空，input:{}, key:{}", input, key);
        }
        return crypted == null ? null : parseByte2HexStr(crypted);
    }

    /**
     * 加密返回,Base64编码字符串
     *
     * @param input 待加密内容
     * @param key   加密密钥
     * @return
     */
    public static String encryptBase64(String input, String key) {
        byte[] crypted = null;
        try {
            SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, skey);
            crypted = cipher.doFinal(input.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (crypted == null) {
            logger.warn("加密结果为空，input:{}, key:{}", input, key);
        }
        return crypted == null ? null : Base64.getEncoder().encodeToString(crypted);
    }

    /**
     * 加密返回,Base64编码字符串
     *
     * @param textBytes 待加密内容
     * @param key       加密密钥
     * @return
     */
    public static byte[] encrypt(byte[] textBytes, String key) {
        byte[] crypted = null;
        try {
            SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, skey);
            crypted = cipher.doFinal(textBytes);
        } catch (Exception e) {
            logger.warn("异常信息：{}", e);
        }
        return crypted;
    }

    /**
     * 解密,返回明文
     *
     * @param input 待解密内容
     * @param key   解密密钥
     * @return
     */
    public static String decrypt(String input, String key) {
        byte[] output = null;
        try {
            SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skey);
            output = cipher.doFinal(parseHexStr2Byte(input));
        } catch (Exception e) {
            logger.warn("异常信息：{}", e);
        }
        if (output == null) {
            logger.warn("解密结果为空，input:{}, key:{}", input, key);
        }
        return output == null ? null : new String(output);
    }

    /**
     * 解密,返回明文
     *
     * @param input 待解密内容
     * @param key   解密密钥
     * @return
     */
    public static String decryptBase64(String input, String key) {
        byte[] output = null;
        try {
            SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skey);
            output = cipher.doFinal(Base64.getDecoder().decode(input));
        } catch (Exception e) {
            logger.warn("异常信息：{}", e);
        }
        if (output == null) {
            logger.warn("解密结果为空，input:{}, key:{}", input, key);
        }
        return output == null ? null : new String(output);
    }

    /**
     * 解密,返回明文
     *
     * @param bytes base64编码的待解密内容
     * @param key   解密密钥
     * @return
     */
    public static String decrypt(byte[] bytes, String key) {
        byte[] output = null;
        try {
            SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skey);
            output = cipher.doFinal(bytes);
        } catch (Exception e) {
            logger.warn("异常信息：{}", e);
        }
        if (output == null) {
            logger.warn("解密结果为空，input:{}, key:{}", bytes, key);
        }
        return output == null ? null : new String(output);
    }


    /**
     * 将二进制转换成16进制
     *
     * @param buf
     * @return
     */
    public static String parseByte2HexStr(byte buf[]) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }
    /**
     * 将16进制转换为二进制
     *
     * @param hexStr
     * @return
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) {
            return null;
        }
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

}
